Ext.ns("liang");

/*******************************************************************************
 * 重写Ext.form.HtmlEditor，为其添加键盘事件 author: hoojo email: hoojo_@126.com blog:
 * http://blog.csdn.net/IBM_hoojo create by: 2010-8-14 ext-lib: 3.2.1 version:
 * 1.0
 */
Ext.override(Ext.form.HtmlEditor, {
			initEditor : function() {
				var dbody = this.getEditorBody();
				var ss = this.el.getStyles('font-size', 'font-family',
						'background-image', 'background-repeat');
				ss['background-attachment'] = 'fixed'; // w3c
				ss['background-color'] = 'white';
				dbody.bgProperties = 'fixed'; // ie
				Ext.DomHelper.applyStyles(dbody, ss);
				if (this.doc) {
					try {
						Ext.EventManager.removeAll(this.doc);
					} catch (e) {
					}
				}
				this.doc = this.getDoc();
				Ext.EventManager.on(this.doc, {
							'mousedown' : this.onEditorEvent,
							'dblclick' : this.onEditorEvent,
							'click' : this.onEditorEvent,
							'keyup' : this.onEditorKeyUpEvent,
							'keydown' : this.onEditorKeyDownEvent,
							'keypress' : this.onEditorKeyPressEvent,
							buffer : 100,
							scope : this
						});
				if (Ext.isGecko) {
					Ext.EventManager.on(this.doc, 'keypress',
							this.applyCommand, this);
				}
				if (Ext.isIE || Ext.isSafari || Ext.isOpera) {
					Ext.EventManager
							.on(this.doc, 'keydown', this.fixKeys, this);
				}
				this.initialized = true;
				this.fireEvent('initialize', this);
				this.doc.editorInitialized = true;
				this.pushValue();
			},
			initComponent : function() {
				this.addEvents('initialize', 'activate', 'beforesync',
						'beforepush', 'sync', 'push', 'editmodechange',
						'keydown', 'keyup', 'keypress');
			},
			onEditorKeyPressEvent : function(e) {
				this.updateToolbar();
				this.fireEvent("keypress", this, e);
			},
			onEditorKeyUpEvent : function(e) {
				this.updateToolbar();
				this.fireEvent("keyup", this, e);
			},
			onEditorKeyDownEvent : function(e) {
				this.updateToolbar();
				this.fireEvent("keydown", this, e);
			}
		});

var viewport;
// 当前在使用的ChatWin
var currentChatWin;

liang.MainWindow = Ext.extend(Ext.Window, {
			xtype : "window",
			title : "web聊天",
			width : 222,
			height : 500,
			autoScroll : false,
			closable : false,
			resizable : false,
			// 显示聊天窗口的方法
			showChatWin : function(obj, evt) {
				// 查找是有相同的IP地址的窗口
				currentChatWin = Ext.getCmp(address)
				if (!currentChatWin) {
					var _nowChatWin = new liang.ChatWin({
								title : "正在与" + address + "聊天",
								user : address,
								ip : address,
								id : address
							});
					currentChatWin = _nowChatWin;
				}
				currentChatWin.show();
			},
			/**
			 * 定时任务 作用：定时刷新在线用户
			 * 
			 * @type
			 */
			taskRefreshOnlineUsers : {
				// 任务间隔，毫秒为单位，这里是10秒
				scope : this,
				interval : 5000,
				run : function() {

				}
			},

			initComponent : function() {
				// 异步树加载器
				var _treeloader = new Ext.tree.TreeLoader({
							url : "chat/Server",
							requestMethod : "get"
						});
				// 右键菜单
				var _menu = new Ext.menu.Menu({
							items : [{
										text : "发送消息",
										handler : this.showChatWin
									}]
						});

				this.items = [{
							xtype : "treepanel",
							border : false,
							baseCls : "x-panil",
							layout : "fit",
							autoScroll : true,
							// 拖动
							// enableDD: true,
							root : new Ext.tree.AsyncTreeNode({
										text : "在线人",
										loader : _treeloader
									}),
							items : [],
							listeners : {
								contextmenu : function(node, evn) {
									if (node.leaf) {
										address = node.id;
										_menu.showAt(evn.getXY());
									}
								}
							}
						}]
				liang.MainWindow.superclass.initComponent.call(this);
			}
		})

liang.ChatWin = Ext.extend(Ext.Window, {
			xtype : "window",
			name : "chatWin",
			// id : "chatWin",
			// title : "正在与XX聊天",
			width : 500,
			height : 400,
			layout : "column",
			autoHeight : false,
			closeAction : "hide",
			// maximizable:true,
			minimizable : true,
			resizable : false,
			minWidth : 500,
			minHeight : 400,
			ip : "",
			user : "",
			sendMsg : function(scope) {
				var _msgPanel = this.find("name", "msgPanel")[0];

				var _editMsg = this.find("name", "editMsg")[0];

				var _val = _editMsg.getValue();
				if (!_val || _val == "" || _val == "<br>")
					return;
				// 添加聊天内容：
				_msgPanel.add({
							border : false,
							html : "我说：<br>" + _val
						});

				// 重新渲染
				_msgPanel.doLayout(true);

				// 移动滚动条显示最新信息
				var _scroll = _msgPanel.body.dom;
				_scroll.scrollTop = _scroll.scrollHeight - _scroll.offsetHeight;

				_editMsg.reset();
				// 发送Ajax请求到后台
				Ext.Ajax.request({
							url : "chat/Server",
							params : {
								receiver : this.id,
								msg : _val,
								action : "sendMsg"
							}
						});
			},
			taskReciveMsg : {
				// 执行任务时执行的函数
				run : function() {
					// 请求后台
					Ext.Ajax.request({
								scope : this,
								url : "chat/Server",
								method : "post",
								disableCaching : true,// 是否禁用缓存,当然要禁用
								timeout : 10000,// 最大等待时间,超出则会触发超时
								success : function(response, option) {// ajax请求发送成功时执行
									// Ext.MessageBox.alert("请求后台数据");
									if (!response
											|| response.responseText == '') {// 返回的内容为空,即服务器停止响应时
										return;
									} else {
										// 解析内容并加载到记录窗口中
										var msgsJson = Ext.util.JSON
												.decode(response.responseText);
										// 取得ChatWin的ID
										var _chatWindID = msgsJson.msgs[0].sender;
										// 获取要加载内容的ChatWin对象
										var _chatWin = Ext.getCmp(_chatWindID);

										var _msgPanel = _chatWin.find("name",
												"msgPanel")[0];
										for (var i = 0; i < msgsJson.msgs.length; i++) {
											msg = msgsJson.msgs[i];
											_msgPanel.add({
														border : false,
														html : msg.sender
																+ "说<br>"
																+ msg.msg
													});
											_msgPanel.doLayout();
										}
										// 移动滚动条显示最新信息
										var _scroll = _msgPanel.body.dom;
										_scroll.scrollTop = _scroll.scrollHeight
												- _scroll.offsetHeight;
									}
								},
								failure : function(data) {// ajax请求发送失败或超时
									Ext.MessageBox.alert(data);
								},
								params : {
									sender : this.address,
									action : 'reciveMsg'
								}
							});
				},
				// 任务间隔，毫秒为单位，这里是10秒
				interval : 5000,
				scope : this
			},
			listeners : {
				show : function(win, evt) {
					// 启动接收信息的定时器
					Ext.TaskMgr.start(win.taskReciveMsg);
				},
				hide : function(win, evt) {
					// 取消接收信息的定时器
					Ext.TaskMgr.stop(win.taskReciveMsg);
				},
				activate : function(win, evt) {
					// Ext.MessageBox.alert(this.ip);
					currentChatWin = win;
				}
			},
			keys : [],
			initComponent : function() {

				var _htmlEdit = new Ext.form.HtmlEditor({
					          scope:this,
							xtype : "htmleditor",
							// fieldLabel : "标签",
							// hideLabel:true,
							// id : "editMsg",
							anchor : "100%",
							name : "editMsg",
							bold : {
								title : 'Bold (Ctrl+B)',
								text : '选择内容设置为粗体',
								cls : 'x-html-editor-tip'
							},
							italic : {
								title : 'Italic (Ctrl+I)',
								text : 'Make the selected text italic.',
								cls : 'x-html-editor-tip'
							},
//							 fontFamilies:[
//							 "宋体",
//							 "粗体"
//							 ],
							height : 128,
							autoWidth : true,
							hidden : false,
							disabled : false,
							enableLinks : false,
							enableFormat : true,
							//enableSourceEdit : true,
							enableFontSize : true,
							enableFont : true,
							enableAlignments : false,
							enableLists : false,
							stateful : true,
							listeners : {
								scope:this,
								"keydown" : function(edit, evt) {
									if (evt.ctrlKey && evt.keyCode == Ext.EventObject.ENTER) {
										  //发送信息   
                                                    this.sendMsg(this);
									}
								}
							}
						});
				var _editPanel = new Ext.Panel({
							xtype : "panel",
							// title:"文本编辑",
							anchor : "100%",
							// layout : "form",
							height : 130,
							autoWidth : true,
							autoScroll : true,
							region : "center",
							items : [_htmlEdit]
						});
				this.items = [{
							xtype : "panel",
							columnWidth : 0.7,
							items : [{
										xtype : "panel",
										anchor : "100%",
										title : "记录",
										name : "msgPanel",
										border : false,
										height : 200,
										autoScroll : true,
										// layout : "fit",
										region : "north",
										html : "",
										// baseCls:"",
										// 因为有样式字体所不能用TextArea控件
										items : []
									}, _editPanel],
							buttons : [{
										text : "发送(ctrl+Enter)",
										scope : this,
										handler : function(obj, evn) {
											this.sendMsg(this);
										}
									}, {
										text : '清空内容',
										width : 40,
										scope : this,
										handler : function(btn, evn) {
											this.find("name", "editMsg")[0]
													.reset();
										}
									}]
						}, {
							xtype : "panel",
							layout : "fit",
							title : "聊天记录",
							height : 500,
							split : true,
							// collapsible : true,
							tools : [{
										id : "left"
									}],
							border : true,
							// autoHeight:true,
							autoScroll : true,
							columnWidth : 0.3
						}];

				liang.ChatWin.superclass.initComponent.call(this);
			},
			keys : [{
						key : [Ext.EventObject.ENTER],
						handler : function() {
							Ext.MessageBox.alter("Enter Key Event !");
						}
					}]
		});

// 输出对象的内容
function print(obj) {
	alert(obj);
	console.dir(obj);
}
Ext.onReady(function() {
	Ext.QuickTips.init();
	var _mainWin = new liang.MainWindow();
	_mainWin.show();
	viewport = new Ext.Viewport();
	viewport.add(_mainWin);

		// var _edit = new Ext.hoo.editor.HTMLEditor();
	});